<?php

namespace App\Console\Commands;

use App\Library\Logic\MessageListLogic;
use App\Library\Logic\MessageLogic;
use App\Library\Logic\ShopCustomerImLogic;
use App\Library\Logic\ShopOrderLogic;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;

class CustomerImCommand extends Command
{
    /**
     * 客服系统同步消息
     *
     * @var string
     */
    protected $signature = 'command:customerIm';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        self::sync();
    }

    private function sync(): void
    {
        $seller = ShopOrderLogic::query()->distinct()->pluck('sell_user_id')->toArray();
        $customerIm = ShopCustomerImLogic::query()->orderBy('ci_id')->get();
        foreach ($customerIm as $val) {
            $model = MessageListLogic::query()->where(function (Builder $builder) use ($val) {
                $builder->where(function (Builder $builder) use ($val) {
                    $builder->where('send_id', $val->receive_user_id)->where('accept_id', $val->send_user_id);
                })->orWhere(function (Builder $builder) use ($val) {
                    $builder->where('send_id', $val->send_user_id)->where('accept_id', $val->receive_user_id);
                });
            })->first();

            if (is_null($model)) {
                MessageListLogic::insertForModel([
                    'sendId' => $val->send_user_id,
                    'acceptId' => $val->receive_user_id,
                    'status' => $val->ci_receive_read === 1 ?? 0,
                    'sendBuyer' => in_array($val->send_user_id, $seller) ?? 0,
                    'update_time' => date('Y-m-d H:i:s', $val->updated_at),
                    'content' => is_null($val->ci_content) ? $val->ci_content_img : $val->ci_content,
                    'createdAt' => now(),
                ]);
            } else {
                $model->send_id = $val->send_user_id;
                $model->accept_id = $val->receive_user_id;
                $model->send_buyer = in_array($val->send_user_id, $seller) ?? 0;
                $model->content = is_null($val->ci_content) ? $val->ci_content_img : $val->ci_content;
                $model->status = $val->ci_receive_read ?? 0;
                $model->update_time = date('Y-m-d H:i:s', $val->updated_at);
                $model->save();
            }

            MessageLogic::insertForModel([
                'sendId' => $val->send_user_id,
                'acceptId' => $val->receive_user_id,
                'status' => $val->ci_receive_read === 1 ?? 0,
                'fileId' => !is_null($val->ci_content_img) ? $val->ci_content_img : null,
                'content' => !is_null($val->ci_content) ? $val->ci_content : null,
            ]);
        }
    }
}
